﻿using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
using Growatt.Shinebus.UI.AutoCal;
using Growatt.ShinebusServiceUploadPack.Service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace Growatt.ShinebusServiceUploadPack.Controllers
{
    /// <summary>
    /// 接收Feishu消息控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class MessageController : ControllerBase
    {
        private readonly HttpClient _httpClient;
        private readonly IServiceProvider serviceProvider;

        public MessageController(IHttpClientFactory clientFactory, IServiceProvider serviceProvider)
        {
            _httpClient = clientFactory.CreateClient();
            _httpClient.DefaultRequestHeaders.Accept.Clear();
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            this.serviceProvider = serviceProvider;
        }

        [HttpPost]
        [Route("receive_message")]
        public async Task<IActionResult> ReceiveMessage([FromBody] JsonElement data)
        {
            try
            {
                if (serviceProvider.GetService<RedisHelper>().messageChannel != null)
                {
                    await serviceProvider.GetService<RedisHelper>().messageChannel.AddMessageToChannelAsync([new EntityObjectData(System.DateTime.Now, 1, [JsonSerializer.Serialize(data)])]);
                }
                // 打印接收到的数据（调试用）
                //_ = new FeishuAPIHelperUsage().SendMessageUrl(new List<string>() { "shuangfeng.chen@growatt.com" }, $"{data}" + Environment.NewLine + $"{System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}" + $"{Environment.NewLine}");
                return Ok(new { status = "success", message = "Data sent successfully" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception occurred: {ex.Message}");
                return StatusCode(500, new { status = "error", message = "Internal server error" });
            }
        }
    }
}
